package com.example.sharedpreferencestest;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private EditText etAccount;
    private EditText etPassword;
    private CheckBox cbRememberPass;
    private Button btnLogin;

    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        preferences = getSharedPreferences("data", MODE_PRIVATE);

        btnLogin = findViewById(R.id.btn_login);
        etAccount = findViewById(R.id.et_account);
        etPassword = findViewById(R.id.et_password);
        cbRememberPass = findViewById(R.id.remember_pass);

        boolean isRemember = preferences.getBoolean("remember_password", false);

        if (isRemember) {
            //如果选择了记住密码，就将账号密码设置到文本框中
            String account = preferences.getString("account", "");
            String password = preferences.getString("password", "");
            etAccount.setText(account);
            etPassword.setText(password);
            cbRememberPass.setChecked(true);
        }

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String account = etAccount.getText().toString();
                String password = etPassword.getText().toString();

                //验证账号密码
                if (account.equals("ls") && password.equals("123456")) {
                    Toast.makeText(MainActivity.this, "登录成功！", Toast.LENGTH_SHORT).show();
                    editor = preferences.edit();
                    if (cbRememberPass.isChecked()) {
                        //如果当前复选框被选中
                        editor.putBoolean("remember_password", true);
                        editor.putString("account", account);
                        editor.putString("password", password);
                    } else {
                        editor.clear();
                    }
                    editor.apply();
                } else {
                    Toast.makeText(MainActivity.this, "账户或密码错误！", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
}
